// components/Authorize/Authorize.js
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false,
    },
    userMsg: {
      type: Object,
      value: {},
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isAllow: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    reject() {
      let { isAllow } = this.data;
      this.triggerEvent('authorization', {
        isShow: false,
        isAllow,
      });
    },
    allow() {
      let { isAllow } = this.data;
      let that = this;

      wx.login({
        success: (res0) => {
          wx.getUserInfo({
            success: (res) => {
              isAllow = true;
              that.setData({
                userMsg: {
                  appId: 'wxba19cfcbe5ecf27d',
                  secret: '1df234e9b883f02e7b1c16b22c09fb0f',
                  code: res0.code,
                },
              });
              app.wxRequest({
                url: `https://api.weixin.qq.com/sns/jscode2session?appid=${that.data.userMsg.appId}&secret=${that.data.userMsg.secret}&js_code=${that.data.userMsg.code}&grant_type=authorization_code`,
                success: (res1) => {
                  res.userInfo.create_time = new Date().getTime();
                  res.userInfo.openid = res1.data.openid;
                  console.log(res.userInfo);
                  app.globalData.userInfo = res.userInfo;
                  that.triggerEvent('authorization', {
                    isShow: false,
                    isAllow,
                  });
                  wx.setStorageSync('userInfo', res.userInfo);
                  wx.cloud
                    .callFunction({
                      name: 'user',
                      data: {
                        type: 'getUserById',
                        id: res1.data.openid,
                      },
                    })
                    .then((res2) => {
                      if (res2.result.data.length === 0) {
                        this.addUser();
                      } else {
                        console.log('存在');
                      }
                    });
                },
              });
            },
          });
        },
      });
    },
    addUser() {
      wx.cloud
        .callFunction({
          name: 'user',
          data: {
            type: 'addUser',
            user: app.globalData.userInfo,
          },
        })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
});
